// NO (INTER-)DEPENDENCIES!

/* List of all the "API" functions:
 * intellifind_db(): see definition!
*/

/* ------------------------
| Compilation Necessities |
-------------------------*/

using namespace std;

#include <pcrecpp.h>
using namespace pcrecpp;

#include <boost/algorithm/string.hpp>
#include <boost/regex.hpp>
using namespace boost;

// DECIDE ABOUT THIS MESS LATER (...)

#ifndef TYPICAL_STRINGS
#define TYPICAL_STRINGS
static const string blank( "" );
#endif

#ifndef PCRE_ICASE
#define PCRE_ICASE
// SQL being case-insensitive,
// our patterns must be too.
static const RE_Options icase( PCRE_CASELESS );
#endif

/* -----------------
| Code starts now! |
----------------- */

// Updates the returned (current) database, by
// default, with a new database, if any, else
// simply continues to return the last database.
// See comments below to check if disconnects
// are disregarded or not!
// Call with reset = true and any dummy string
// in order to forget the current (or last used)
// database when working with multiple logs.
string intellifind_db( const string& s, const bool& reset = false ){

	static const RE db_fiddle( "^DEBUG:\\s+(connection|disconnect): ", icase );
	static const RE db_disconn( "^DEBUG:\\s+(disconnect): ", icase );
	static const RE database_name( "\\b(database)=([^\\s]+)", icase ); // Grouping counts!
	static string current_db = blank, last = blank;

	if( reset ){
		current_db = blank;
		last = blank;
		return string( "/" );
	}

	if( db_fiddle.PartialMatch( s ) ){
		string dummy, dbn;
		assert( database_name.PartialMatch( s, &dummy, &dbn ) );
		if( db_disconn.PartialMatch( s ) ){
			if( dbn != current_db ){
				if( !current_db.empty() ){
					// Uncomment to see mismatched database "unloads".
					/*cerr << "Warning: Mismatched database (" << dbn << ") disconnected!" << endl
							<< "Currently (considered) loaded: " << current_db << endl;//*/
				}
			}
			else{
				last = current_db;
				// Uncomment to consider "disconnects"!
				// However, subsequent successful runs
				// have not been fully verified...
				//current_db = blank;
			}
		}
		else{
			current_db = dbn;
			if( current_db != last ){
				// Uncomment to track changes in
				// the "currently" loaded database!
				//cerr << current_db << endl;
				last = current_db;
			}
		}
	}

	return current_db;

}
